///
/// 张诚宇
/// 网络工具类
///

import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhangchengyu20220614/model/httpinterceptor.dart';


typedef SUCCESS = void Function(dynamic);
typedef ERROR = void Function(int,String);

class NetWorkManaget{
  static NetWorkManaget _netWorkManaget = NetWorkManaget._instance();
  Dio _dio;

  NetWorkManaget._instance(){
    _dio = Dio(
      BaseOptions(
        receiveTimeout: 5000,
        connectTimeout: 5000,
        sendTimeout: 5000
      )
    );
    _dio.interceptors.addAll([HttpInterceptor(),LogInterceptor(requestBody: true,responseBody: true),DioCacheManager(CacheConfig()).interceptor]);
  }

  factory NetWorkManaget(){
    return _netWorkManaget;
  }

  netWorkGet(String path,{Map<String,dynamic> map,SUCCESS onSuccess,ERROR onError,bool isCache=false}) async{
    try{
      var response = await _dio.get(path,queryParameters: map,options: isCache ? buildCacheOptions(Duration(days: 7)) : null);
      onSuccess(response.data);
    }on DioError catch(e){
      onError(e.response.statusCode,e.response.statusMessage);
      Fluttertoast.showToast(msg: '${e.response.statusCode}');
    }
  }
  netWorkPost(String path,{Map<String,dynamic> map,Map<String,dynamic> map2,SUCCESS onSuccess,ERROR onError,bool isCache=false}) async{
    try{
      var response = await _dio.post(path,queryParameters: map,data: map2,options: isCache ? buildCacheOptions(Duration(days: 7)) : null);
      onSuccess(response.data);
    }on DioError catch(e){
      onError(e.response.statusCode,e.response.statusMessage);
      Fluttertoast.showToast(msg: '${e.response.statusCode}');
    }
  }

}